//
//  UserCenter.m
//  PalmHospitalTongJi
//
//  Created by leon on 13-11-20.
//  Copyright (c) 2013年 lvxian. All rights reserved.
//

#import "UserCenter.h"
#import "taskUserService.h"
//#import "dataGetUser.h"

@interface UserCenter()

@end

@implementation UserCenter
@synthesize authToken = _authToken;
@synthesize userNo = _userNo;
@synthesize isLogined = _isLogined;
@synthesize user = _user;

+ (instancetype)shareCenter
{
    static UserCenter* center;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        center = [[UserCenter alloc] init];
    });
    return center;
}

- (id)init
{
    if(self = [super init]){
        _user = [self getProfileDisk];
        _authToken = [[NSUserDefaults standardUserDefaults] objectForKey:SAVE_KEY_AUTH];
    }
    return self;
}

- (NSString*)authToken
{
    if(!_authToken){
        _authToken = @"";
    }
    return _authToken;
}


//true:已登录，false:未登录
- (BOOL)isLogined
{
    return _authToken != nil && _authToken.length > 0;
}

#pragma mark - 退出登录

- (void)logout:(void (^)(BOOL suc, NSString* error))completion{
    
    [self clearUserState];
    completion(YES,@"退出成功");
//    [DKProgressHUD showLoading];
//    NSMutableDictionary *dict = [NSMutableDictionary new];
//    [dict setValue:[UserCenter shareCenter].user.UserId forKeyPath:@"uphone"];
//    [dict setValue:[UserCenter shareCenter].user.pid forKeyPath:@"uid"];
//    [taskUserManagerService getLoginOut:dict success:^(BaseModel *response, BOOL success) {
//        [DKProgressHUD dismiss];
//        completion(success,response.message);
//    } failture:^(NSError *error, NSString *strDescription) {
//         [DKProgressHUD dismiss];
//        completion(NO,strDescription);
//    }];
}

-(void)clearUserState{
    _user = nil;
    _authToken = nil;

    [[NSUserDefaults standardUserDefaults] removeObjectForKey:SAVE_KEY_AUTH];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:SAVE_KEY_PROFILE];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

//#pragma mark - user profile info
//
//
/**
 *  获取用户信息---调接口
 *
 */
- (void)getProfileRemote:(void (^)(modelUserInfo * profile))completitonOK err:(void (^)(NSString * str))completitonFail {

    if (_userNo == nil) {
        UIViewController *tabView=(UIViewController*)[UIApplication sharedApplication].keyWindow.rootViewController;
        LoginNavigationController *login = [[LoginNavigationController alloc]init];
        [tabView presentViewController:login animated:YES completion:nil];
        return;
    }
    
    NSMutableDictionary *dict = [NSMutableDictionary new];
    [dict setValue:_userNo forKey:@"username"];
    __weak __typeof(self)weakSelf = self;
    [taskUserService getUserInfo:dict success:^(modelUserData *response, BOOL success) {
        if (success) {
            weakSelf.user = response.data;
            weakSelf.userNo = response.data.member.username;
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSData* userObj = [weakSelf.user mj_JSONData];
                if(userObj){
                    [[NSUserDefaults standardUserDefaults] setValue:userObj forKey:SAVE_KEY_PROFILE];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                }
            });
            if (!response.data) {
                [DKProgressHUD showErrorWithStatus:@"获取用户信息失败,请重新登录"];
            }
            completitonOK(self.user);
        }

    } failture:^(NSError *error, NSString *strDescription) {
        [DKProgressHUD dismiss];
        completitonFail(strDescription);
    }];
}

///**
// *  获取用户信息----取本地数据--
// *
// */
- (modelUserInfo *)getProfileDisk
{
    NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:SAVE_KEY_PROFILE];
    if (data) {
        NSString *strJson = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSData * data = [strJson dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
       modelUserInfo *profile =  [modelUserInfo mj_objectWithKeyValues:dict];
        return profile;
    }
    return nil;
}

///**
// *  刷新用户信息本地数据存储
// *
// *  @param completiton <#completiton description#>
// */
- (void)refreshProfiles:(void (^)(modelUserInfo * profile))completiton
{
    [self getProfileRemote:^(modelUserInfo *profile) {
        self.user = profile;
        completiton(profile);
    } err:^(NSString *str) {
        self.user = nil;
    }];
}

/**
 *  获取用户信息---自动筛选
 */
- (void)getProfiles:(void (^)(modelUserInfo * pUser))completiton{
    modelUserInfo *profile = [self getProfileDisk];
    if (profile && profile.member.pid > 0) {
        if(completiton){
            self.user = profile;
            completiton(profile);
        }
    }else{

        [self getProfileRemote:^(modelUserInfo *profile) {
            if(completiton){
                self.user = profile;
                NSData* userObj = [profile mj_JSONData];
                [[NSUserDefaults standardUserDefaults] setValue:userObj forKey:SAVE_KEY_PROFILE];
                [[NSUserDefaults standardUserDefaults] synchronize];
                completiton(profile);
            }
        } err:^(NSString *str) {
            [DKProgressHUD showErrorWithStatus:str];
            NSLog(@"获取用户信息失败：%@",str);
            [self logout:^(BOOL suc, NSString *error) {
               UIViewController *vc = [self topViewController];
                [vc.navigationController popToRootViewControllerAnimated:YES];
            }];
            return;
        }];
    }
}

#pragma mark - 获取当前主窗体的viewcontroller


- (UIViewController *)topViewController {
    UIViewController *resultVC;
    resultVC = [self _topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
    while (resultVC.presentedViewController) {
        resultVC = [self _topViewController:resultVC.presentedViewController];
    }
    return resultVC;
}

- (UIViewController *)_topViewController:(UIViewController *)vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [self _topViewController:[(UINavigationController *)vc topViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [self _topViewController:[(UITabBarController *)vc selectedViewController]];
    } else {
        return vc;
    }
    return nil;
}

@end
